package com.alibaba.algo.apiimpl.user;

import com.alibaba.algo.cooperation.common.BaseResult;
import com.alibaba.algo.cooperation.usercomponent.service.user.FileService;
import com.alibaba.algo.util.StringUtil;
import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Service;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.nio.charset.StandardCharsets;

/**
 * @author : WangZhiPan
 * @date : 2021/11/2 14:30
 */
@Service
@ConfigurationProperties(prefix = "sys.templates")
@Slf4j
public class FileServiceImpl implements FileService {
    private String path;
    private static final String DEFAULT_PATH = "templates";


    /**
     * 错误信息处理  1，构造异常提示返回流，2，记录log
     *
     * @param msg
     * @param os
     */
    private void errorHandle(String msg, ServletOutputStream os) {
        BaseResult resp = BaseResult.buildError(msg);
        byte[] bytes;
        bytes = JSON.toJSONString(resp).getBytes(StandardCharsets.UTF_8);
        try {
            os.write(bytes);
        } catch (IOException e) {
            log.error("io error", e);
        }
        log.error(msg);
    }


    /**
     * 下载模板,请求api传递文件名即可
     * 支持开辟一个路径（默认在类路径/templates）存放模板文件，提供给前端下载，满足导入数据时提供给用户的文件模板
     * 支持sys.template.path灵活配置模板路径
     *
     * @param request
     * @param response
     * @param fileName 文件名称，默认Template-SysOrg.xlsl
     */
    @Override
    public void downloadTemplate(HttpServletRequest request, HttpServletResponse response, String fileName) {
        path = StringUtil.isEmpty(path) ? Thread.currentThread().getContextClassLoader().getResource(".").getPath() + DEFAULT_PATH : path;
        fileName = StringUtil.isEmpty(fileName) ? "Template-SysOrg.xlsl" : fileName;
        File file = new File(path, fileName);
        ServletOutputStream os = null;
        response.setContentType("application/json;charset=UTF-8");
        try {
            os = response.getOutputStream();
            if (!file.exists()) {
                errorHandle("文件不存在：" + fileName, os);
                return;
            }
            String isoName = null;
            try {
                isoName = new String(fileName.getBytes("GB2312"), StandardCharsets.ISO_8859_1);
            } catch (UnsupportedEncodingException e) {
                log.error("getByte error=={}", e.getMessage());
                errorHandle("字符转换异常，请联系后台管理员处理", os);
                return;
            }
            byte[] buffer = new byte[1024];
            FileInputStream fis = null;
            BufferedInputStream bis = null;
            try {
                fis = new FileInputStream(file);
                bis = new BufferedInputStream(fis);
                int i;
                while ((i = bis.read(buffer)) != -1) {
                    os.write(buffer, 0, i);
                }
                response.setHeader("Content-Disposition", "attachment;fileName=" + isoName);
                response.setContentType(null);
            } catch (FileNotFoundException e) {
                errorHandle("文件不存在，文件：" + fileName, os);
                return;
            } finally {
                log.info("start close~~~~~");
                if (bis != null) {
                    bis.close();
                }
                if (fis != null) {
                    fis.close();
                }
            }
        } catch (IOException e) {
            errorHandle("IO异常，请联系系统管理员：" + fileName, os);
            return;
        }
    }
}
